package org.dromara.bykt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.bykt.domain.BYKTCourseVideo;
import org.dromara.bykt.domain.vo.BYKTCourseChapterListVO;
import org.dromara.bykt.domain.vo.BYKTCourseVideoVo;
import org.dromara.bykt.mapper.BYKTCourseVideoMapper;
import org.dromara.bykt.service.IBYKTCourseVideoService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.bykt.domain.bo.BYKTCourseChapterBo;
import org.dromara.bykt.domain.vo.BYKTCourseChapterVo;
import org.dromara.bykt.domain.BYKTCourseChapter;
import org.dromara.bykt.mapper.BYKTCourseChapterMapper;
import org.dromara.bykt.service.IBYKTCourseChapterService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 课程章节Service业务层处理
 *
 * @author Hou
 * @date 2025-06-22
 */
@RequiredArgsConstructor
@Service
public class BYKTCourseChapterServiceImpl implements IBYKTCourseChapterService {

    private final BYKTCourseChapterMapper baseMapper;

    @Autowired
    private IBYKTCourseVideoService ibyktCourseVideoService;

    @Autowired
    private BYKTCourseVideoMapper baseVideoMapper;

    /**
     * 查询课程章节
     *
     * @param id 主键
     * @return 课程章节
     */
    @Override
    public BYKTCourseChapterVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询课程章节列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 课程章节分页列表
     */
    @Override
    public TableDataInfo<BYKTCourseChapterVo> queryPageList(BYKTCourseChapterBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BYKTCourseChapter> lqw = buildQueryWrapper(bo);
        Page<BYKTCourseChapterVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的课程章节列表
     *
     * @param bo 查询条件
     * @return 课程章节列表
     */
    @Override
    public List<BYKTCourseChapterVo> queryList(BYKTCourseChapterBo bo) {
        LambdaQueryWrapper<BYKTCourseChapter> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BYKTCourseChapter> buildQueryWrapper(BYKTCourseChapterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BYKTCourseChapter> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BYKTCourseChapter::getId);
        lqw.eq(bo.getCourseId() != null, BYKTCourseChapter::getCourseId, bo.getCourseId());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), BYKTCourseChapter::getTitle, bo.getTitle());
        lqw.eq(bo.getSort() != null, BYKTCourseChapter::getSort, bo.getSort());
        return lqw;
    }

    /**
     * 新增课程章节
     *
     * @param bo 课程章节
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BYKTCourseChapterBo bo) {
        BYKTCourseChapter add = MapstructUtils.convert(bo, BYKTCourseChapter.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改课程章节
     *
     * @param bo 课程章节
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BYKTCourseChapterBo bo) {
        BYKTCourseChapter update = MapstructUtils.convert(bo, BYKTCourseChapter.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BYKTCourseChapter entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除课程章节信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> nonExistingIds = new ArrayList<>(ids);
            for (Long id : nonExistingIds) {
                Long aLong = ibyktCourseVideoService.queryChapterId(id);
                if (aLong != 0l) {
                    throw new ServiceException("以下章节ID被视频使用，无法删除:" + id);
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<BYKTCourseChapterListVO> queryChapterList(BYKTCourseChapterBo bo) {
        List<BYKTCourseChapterListVO> chapterListVOS = new ArrayList<>();
        List<BYKTCourseVideoVo> byktCourseVideoVoList =  new ArrayList<>();
        QueryWrapper<BYKTCourseChapter> chapterQueryWrapper = new QueryWrapper<>();
        if (bo.getCourseId() != null) {
            chapterQueryWrapper.lambda().eq(BYKTCourseChapter::getCourseId, bo.getCourseId());
        }
        if(bo.getTitle() != null && !"".equals(bo.getTitle())){
            chapterQueryWrapper.lambda().like(BYKTCourseChapter::getTitle, bo.getTitle());
        }
        List<BYKTCourseChapterVo> byktCourseChapterVos = baseMapper.selectVoList(chapterQueryWrapper);
        if (!byktCourseChapterVos.isEmpty()) {
            for (BYKTCourseChapterVo byKTCourseChapterVo : byktCourseChapterVos) {
                BYKTCourseChapterListVO byKTCourseChapterListVO = new BYKTCourseChapterListVO();
                byKTCourseChapterListVO.setId(byKTCourseChapterVo.getId());
                byKTCourseChapterListVO.setCourseId(byKTCourseChapterVo.getCourseId());
                byKTCourseChapterListVO.setTitle(byKTCourseChapterVo.getTitle());
                byKTCourseChapterListVO.setExpanded(true);
                byKTCourseChapterListVO.setType(2);
                QueryWrapper<BYKTCourseVideo> videoQueryWrapper = new QueryWrapper<>();
                videoQueryWrapper.lambda().eq(BYKTCourseVideo::getChapterId, byKTCourseChapterVo.getId());
                List<BYKTCourseVideoVo> byktCourseVideoVos = baseVideoMapper.selectVoList(videoQueryWrapper);
                if (!byktCourseVideoVos.isEmpty()) {
                    for (BYKTCourseVideoVo byKTCourseVideoVo : byktCourseVideoVos) {
                        byKTCourseVideoVo.setType(3);
                        byKTCourseVideoVo.setExpanded(true);
                        byktCourseVideoVoList.add(byKTCourseVideoVo);
                    }
                }
                byKTCourseChapterListVO.setVideoList(byktCourseVideoVos);
                chapterListVOS.add(byKTCourseChapterListVO);
            }
        } else {
            QueryWrapper<BYKTCourseVideo> videoQueryWrapper = new QueryWrapper<>();
            videoQueryWrapper.lambda().eq(BYKTCourseVideo::getTitle, bo.getTitle());
            List<BYKTCourseVideoVo> byktCourseVideoVos = baseVideoMapper.selectVoList(videoQueryWrapper);
            if (!byktCourseVideoVos.isEmpty()) {
                for (BYKTCourseVideoVo byKTCourseVideoVo : byktCourseVideoVos) {
                    byKTCourseVideoVo.setType(3);
                    byKTCourseVideoVo.setExpanded(true);
                    byktCourseVideoVoList.add(byKTCourseVideoVo);
                }
                for (BYKTCourseVideoVo byKTCourseVideoVo : byktCourseVideoVos) {
                    QueryWrapper<BYKTCourseChapter> chapterWrapper = new QueryWrapper<>();
                    chapterWrapper.lambda().eq(BYKTCourseChapter::getId, byKTCourseVideoVo.getChapterId());
                    List<BYKTCourseChapterVo> ChapterVos = baseMapper.selectVoList(chapterWrapper);
                    if (!ChapterVos.isEmpty()) {
                        for (BYKTCourseChapterVo byKTCourseChapterVo : ChapterVos) {
                            BYKTCourseChapterListVO byKTCourseChapterListVO = new BYKTCourseChapterListVO();
                            byKTCourseChapterListVO.setId(byKTCourseChapterVo.getId());
                            byKTCourseChapterListVO.setCourseId(byKTCourseChapterVo.getCourseId());
                            byKTCourseChapterListVO.setTitle(byKTCourseChapterVo.getTitle());
                            byKTCourseChapterListVO.setExpanded(true);
                            byKTCourseChapterListVO.setType(2);
                            byKTCourseChapterListVO.setVideoList(byktCourseVideoVos);
                            chapterListVOS.add(byKTCourseChapterListVO);
                        }
                    }
                }
            }
        }
        return chapterListVOS;
    }

    @Override
    public Long queryCourseId(Long courseId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BYKTCourseChapter>().eq(BYKTCourseChapter::getCourseId, courseId));
    }
}
